package com.example.car_lrp_plugin

import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.view.View
import com.pcl.ocr.scanner.ScannerOptions
import com.pcl.ocr.scanner.ScannerView
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView
import org.opencv.android.BaseLoaderCallback
import org.opencv.android.LoaderCallbackInterface
import org.opencv.android.OpenCVLoader

/**
 *@packageName com.example.car_lrp_plugin
 *@author kzcai
 *@date 2022/2/10
 */
class CarLrpView(private val context: Context):PlatformView,MethodChannel.MethodCallHandler {

    private val scannerView = ScannerView(context)

    override fun getView(): View {
        return scannerView
    }

    private fun startCamera(){
        val builder = ScannerOptions.Builder()
            .setTipText("请将识别车牌放入框内")
            .setFrameCornerColor(0xFF26CEFF.toInt())
            .setLaserLineColor(0xFF26CEFF.toInt())
            .build()
        scannerView.setScannerOptions(builder)
        scannerView.setOnScannerOCRListener {cardNum ->

        }

    }

    override fun dispose() {

    }

    private fun initOpenCv(){
        if (!OpenCVLoader.initDebug()) {
            Log.d(
                "OpenCV",
                "Internal OpenCV library not found. Using OpenCV Manager for initialization"
            )
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_4_0, context, mLoaderCallback)
        } else {
            Log.d("OpenCV", "OpenCV library found inside package. Using it!")
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS)
        }
    }

    private val mLoaderCallback: BaseLoaderCallback = object : BaseLoaderCallback(context) {
        @SuppressLint("StaticFieldLeak")
        override fun onManagerConnected(status: Int) {
            if (status == SUCCESS) {
                System.loadLibrary("lpr")
            } else {
                super.onManagerConnected(status)
            }
        }
    }

    override fun onMethodCall(p0: MethodCall, p1: MethodChannel.Result) {
        if (p0.method=="startScan"){
            startCamera()
        }else if (p0.method=="init"){
            initOpenCv()
        }

    }
}